package common

import (
	"errors"
	"fmt"
	"time"
)

// 代表包含高负载操作的函数
type OpFunc func() error

func Execute(op OpFunc, times int) (err error) {
	if op == nil {
		return errors.New("操作函数为nil")
	}
	if times <= 0 {
		return fmt.Errorf("执行次数不可用: %d", times)
	}
	var startTime time.Time
	defer func() {
		diff := time.Now().Sub(startTime)
		fmt.Printf("执行持续时间: %s\n", diff)
		if p := recover(); p != nil {
			err = fmt.Errorf("fatal error: %v", p)
		}
	}()
	startTime = time.Now()
	for i := 0; i < times; i++ {
		if err = op(); err != nil {
			return
		}
		time.Sleep(time.Microsecond)
	}
	return
}
